package com.canbot.u05.activity.shoppingGuide.sales;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;

import com.alibaba.fastjson.JSON;
import com.canbot.u05.R;
import com.canbot.u05.activity.BaseActivityNoTitle;
import com.canbot.u05.activity.customvoice.ChooseAudioActivity;
import com.canbot.u05.activity.shoppingGuide.ShoppingChooseAudioActivity;
import com.canbot.u05.bean.sales.RouteGuide;
import com.canbot.u05.network.SalesApi;
import com.canbot.u05.socket.IpMsgConst;
import com.canbot.u05.update.StringUtils;
import com.canbot.u05.utils.Logger;
import com.canbot.u05.utils.OkHttpUtils;
import com.canbot.u05.utils.SPUtils;
import com.canbot.u05.utils.ToastTools;
import com.canbot.u05.view.RouteRecordDialog;
import com.canbot.u05.widget.LoadingDialogUtils;

import java.io.File;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class SpeechSetupActivity extends BaseActivityNoTitle implements View.OnClickListener {

        private RelativeLayout rlLocalSpeech;

        private static final int REQUEST_SPEECH = 101;

        private static final int REQUEST_TEXT = 102;

        private static final int REQUEST_RECORD = 103;


        private RelativeLayout rlTextToSpeech;

        private RelativeLayout rlRecord;

        private RouteRecordDialog usherModeRecordDialog;

        private String fileName;

        private String title;

        private String address;

        private String pic;

        private String path;

        private String ttsResult;

        private int type = -1;

        private String edit;

        private String id;

        private String voice;

        private int type1;

        private static final int HEAD_SEED_MESSAGE_SUCCESS = 101;

        private static final int HEAD_SEED_MESSAGE_FAILURE = 102;

        private static final int HEAD_EDIT_MESSAGE_SUCCESS = 201;

        private static final int HEAD_EDIT_MESSAGE_FAILURE = 202;
        private static final int TIMEOUT = 100;//超时时间100s

        private Handler mHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                        super.handleMessage(msg);

                        switch (msg.what) {
                                case HEAD_SEED_MESSAGE_SUCCESS:
                                        addRouteToChest();
                                        break;
                                case HEAD_SEED_MESSAGE_FAILURE:
                                        //addRoute();
                                        break;
                                case HEAD_EDIT_MESSAGE_SUCCESS:
                                        editRouteChest();
                                        break;
                                case HEAD_EDIT_MESSAGE_FAILURE:
                                        break;
                        }

                }
        };

        private String uuid;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_speech_setup);
                initView();
                initEvent();
        }

        @Override
        protected void onResume() {
                super.onResume();
//                MsgSendUtils.sendStringMsg(MsgType.SENT_PAD_ENTER_ROUTE_SETUP_VOICE,"enter route voice");
        }

        @Override
        protected void onDestroy() {
                super.onDestroy();
                this.edit = "";
                this.title = "";
                this.address = "";
                this.pic = "";
                mHandler.removeMessages(HEAD_SEED_MESSAGE_SUCCESS);
                mHandler.removeMessages(HEAD_SEED_MESSAGE_FAILURE);
                mHandler.removeMessages(HEAD_EDIT_MESSAGE_SUCCESS);
                mHandler.removeMessages(HEAD_EDIT_MESSAGE_FAILURE);
        }


        private void initEvent() {

                rlLocalSpeech.setOnClickListener(this);
                rlTextToSpeech.setOnClickListener(this);
                rlRecord.setOnClickListener(this);
        }

        private void initView() {
                rlLocalSpeech = (RelativeLayout) findViewById(R.id.rl_local_speech);
                rlTextToSpeech = (RelativeLayout) findViewById(R.id.rl_text_to_speech);
                rlRecord = (RelativeLayout) findViewById(R.id.rl_record);
                Intent intent = getIntent();

                String edit = intent.getStringExtra("edit");
                String title = intent.getStringExtra("title");
                String address = intent.getStringExtra("address");
                String pic = intent.getStringExtra("pic");
                this.edit = edit;
                this.title = title;
                this.address = address;
                this.pic = pic;
                if (!StringUtils.isEmpty(edit)) {
                        //id = intent.getIntExtra("id", -1);
                        id = intent.getStringExtra("id");
                        voice = intent.getStringExtra("voice");
                        path = voice;
                        type1 = intent.getIntExtra("type", -1);
                        type = type1;
                        if (type == 0) {
                                selected(true, false, false);
                        }
                        else if (type == 1) {
                                selected(false, true, false);
                        }
                        else if (type == 2) {
                                selected(false, false, true);
                        }

                }


        }

        /**
         * 返回
         *
         * @param view
         */
        public void back(View view) {
                finish();
                overridePendingTransition(R.anim.face_zoom_enter,
                        R.anim.face_zoom_exit);
        }

        /**
         * 选择完语音后提交添加的线路信息
         *
         * @param view
         */
        public void complete(View view) {
                if ("speech".equals(edit)) {
                        Log.d("SpeechSetupActivity", "SpeechSetupActivity" + "修改语音");
                        editRouteChest();
                }
                else {
                        if (TextUtils.isEmpty(path)){
                                ToastTools.newInstance(this).showText(getString(R.string.answer_cannot_empty));
                                return;
                        }
                        Log.d("SpeechSetupActivity", "SpeechSetupActivity" + "创建语音");
                        addRouteToChest();
                        //addRouteToChest();
                }

        }

        private Dialog dialogLoading;


        /**
         * 修改语音
         */
        private void editRouteChest() {
                dialogLoading = LoadingDialogUtils.createLoadingDialog(this, getString(R.string.updating));
                RouteGuide routeGuide = new RouteGuide();
                routeGuide.setId(id);
                routeGuide.setVoice(path);
                routeGuide.setType(type);

                String jsonString = JSON.toJSONString(routeGuide);
                Log.d("SpeechSetupActivity", "访问地址" + "http://" + IpMsgConst.CHEST_SOCKET_HOST + ":7755");

                Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl("http://" + IpMsgConst.CHEST_SOCKET_HOST + ":7755")
                        .addConverterFactory(GsonConverterFactory.create())
                        .client(setTimeOut())
                        .build();
                SalesApi salesApi = retrofit.create(SalesApi.class);
                Call<String> stringCall = salesApi.editSpeechInfo(jsonString);
                stringCall.enqueue(new Callback<String>() {
                        @Override
                        public void onResponse(Call<String> call, Response<String> response) {
                                String code = response.body();
                                if ("0".equals(code)) {
                                        LoadingDialogUtils.closeDialog(dialogLoading);
                                        ToastTools.newInstance(SpeechSetupActivity.this).showText(getString(R.string.modify_successfully));
                                        finish();
                                        overridePendingTransition(R.anim.face_zoom_enter,
                                                R.anim.face_zoom_exit);
                                }
                                else {
                                        ToastTools.newInstance(SpeechSetupActivity.this).showText(getString(R.string.modify_failed));
                                        finish();
                                        overridePendingTransition(R.anim.face_zoom_enter,
                                                R.anim.face_zoom_exit);
                                }
                        }

                        @Override
                        public void onFailure(Call<String> call, Throwable t) {
                                ToastTools.newInstance(SpeechSetupActivity.this).showText(getString(R.string.modify_failed));
                                finish();
                                overridePendingTransition(R.anim.face_zoom_enter,
                                        R.anim.face_zoom_exit);
                        }
                });


        }


        /**
         * 往胸口添加数据
         */
        private void addRouteToChest() {
                uuid = UUID.randomUUID().toString().replace("-", "");
                dialogLoading = LoadingDialogUtils.createLoadingDialog(this, getString(R.string.data_upload));
                RouteGuide routeGuide = new RouteGuide();
                routeGuide.setId(uuid);
                routeGuide.setTitle(title);
                routeGuide.setAddress(address);
                routeGuide.setVoice(path);
                routeGuide.setType(type);
                routeGuide.setPic(pic);

                String jsonString = JSON.toJSONString(routeGuide);
                Log.d("SpeechSetupActivity", "访问地址" + "http://" + IpMsgConst.CHEST_SOCKET_HOST + ":7755");

                Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl("http://" + IpMsgConst.CHEST_SOCKET_HOST + ":7755")
                        .addConverterFactory(GsonConverterFactory.create())
                        .client(setTimeOut())
                        .build();
                SalesApi salesApi = retrofit.create(SalesApi.class);
                Call<String> stringCall = salesApi.addRouteInfo(jsonString);
                stringCall.enqueue(new Callback<String>() {
                        @Override
                        public void onResponse(Call<String> call, Response<String> response) {
                                Log.d("SpeechSetupActivity", "添加内容 " + response.body() + "");
                                String result = response.body();
                                if ("0".equals(result)) {
                                        LoadingDialogUtils.closeDialog(dialogLoading);
                                        finish();
                                        overridePendingTransition(R.anim.face_zoom_enter,
                                                R.anim.face_zoom_exit);

                                        ToastTools.newInstance(SpeechSetupActivity.this).showText(getString(R.string.upload_complete));

                                }
                                else {
                                        LoadingDialogUtils.closeDialog(dialogLoading);
                                        ToastTools.newInstance(SpeechSetupActivity.this).showText(getString(R.string.upload_failed));
                                }
                        }

                        @Override
                        public void onFailure(Call<String> call, Throwable t) {
                                LoadingDialogUtils.closeDialog(dialogLoading);
                                t.printStackTrace();
                                Logger.d("SpeechSetupActivity", "胸口上传失败");
                                ToastTools.newInstance(SpeechSetupActivity.this).showText(getString(R.string.upload_failed));
                        }
                });
        }

        @Override
        public void onClick(View view) {
                switch (view.getId()) {
                        case R.id.rl_local_speech:

                                Intent i = new Intent(SpeechSetupActivity.this, ChooseAudioActivity.class);
                                i.putExtra("path", "/uusound");
                                if (!TextUtils.isEmpty(voice)){
                                        if (type == 0){
                                                i.putExtra("voice", voice);
                                        }

                                }

                                startActivityForResult(i, REQUEST_SPEECH);
                                break;
                        case R.id.rl_text_to_speech:
                                Intent intent2 = new Intent(SpeechSetupActivity.this, TextToSpeechActivity.class);
                                if (!TextUtils.isEmpty(voice)){
                                        if (type == 1){
                                                intent2.putExtra("voice", voice);
                                        }

                                }
                                startActivityForResult(intent2, REQUEST_TEXT);
                                break;
                        case R.id.rl_record:
                                record();
                                break;

                        case R.id.record_dialog_finish:
                                fileName = usherModeRecordDialog.ok();
                                Logger.e("test", "fileName" + fileName);
                                usherModeRecordDialog.setTime(SpeechSetupActivity.this.getString(R.string.uploading_please_wait));
                                Logger.d("SpeechSetupActivity", "录音的文件名：" + fileName);
                                updataFile();

                                break;
                        case R.id.record_dialog_cancle:
                                usherModeRecordDialog.no();
                                //finish();
                                usherModeRecordDialog.dismiss();
                                Logger.d("SpeechSetupActivity", "录音的文件名：" + fileName);
                                break;
                        default:
                                break;
                }

                overridePendingTransition(R.anim.face_zoom_enter,
                        R.anim.face_zoom_exit);
        }

        /**
         * 进入录音
         */
        private void record() {
                if (usherModeRecordDialog == null) {
                        //点击语音录入图标
                        usherModeRecordDialog = new RouteRecordDialog(this, RouteRecordDialog.USHER_MODE);
                        usherModeRecordDialog.setFinishClickListener(this);
                        usherModeRecordDialog.setCancleClickListener(this);
                        setDialogWindowAttr(usherModeRecordDialog, this);
                        usherModeRecordDialog.show();
                }
                else {
                        usherModeRecordDialog.show();
                }

        }

        public static void setDialogWindowAttr(Dialog dlg, Context ctx) {
                dlg.setCancelable(false);
                Window window = dlg.getWindow();
                WindowManager.LayoutParams lp = window.getAttributes();
                lp.gravity = Gravity.CENTER;
                lp.width = (int) ctx.getResources().getDimension(R.dimen.x536);//宽高可设置具体大小
                lp.height = (int) ctx.getResources().getDimension(R.dimen.x436);
                dlg.getWindow().setAttributes(lp);
        }

        //上传到机器人头部的某个文件夹下
        private String url = IpMsgConst.HTTP_URL + "uploadRecord";

        private void updataFile() {
                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put("audiofile", new File(RouteRecordDialog.RECORD_FILE_DIR, fileName));
                hashMap.put("path", fileName);
                OkHttpUtils.upLoadFile(url, hashMap, new OkHttpUtils.OkHttpCallBack() {
                        @Override
                        public void onSuccess(String result) {
                                Logger.e("test", result + "上传成功");
                                usherModeRecordDialog.cancel();
                                SPUtils.saveBoolean(SpeechSetupActivity.this, "isTTS", false);
                                runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                                selected(false, false, true);
                                                ToastTools.newInstance(SpeechSetupActivity.this).showText(getString(R.string.upload_complete));
                                        }
                                });
                                path = fileName;
                                type = 2;

                                //Intent intent = new Intent();
                                //intent.putExtra("type", 3);
                                //setResult(102, intent);
                                //finish();
                                usherModeRecordDialog.dismiss();
                                //rlRecord.setSelected(true);


                        }

                        @Override
                        public void onFailure() {
                                usherModeRecordDialog.cancel();
                                runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                                ToastTools.newInstance(SpeechSetupActivity.this).showText(getString(R.string.upload_failed));
                                        }
                                });
                                //finish();
                                usherModeRecordDialog.dismiss();

                        }
                });
        }

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                super.onActivityResult(requestCode, resultCode, data);

                if (resultCode == RESULT_CANCELED){
                        return;
                }
                if (requestCode == REQUEST_SPEECH ) {
                        path = data.getStringExtra("path");
                        Logger.d("SpeechSetupActivity", "选中的语音路径 ：" + path);
                        if (!StringUtils.isEmpty(path)) {
                                type = 0;
                                selected(true, false, false);
                        }
                }

                if (requestCode == REQUEST_TEXT ) {
                        path = data.getStringExtra("ttsResult");
                        boolean isChecked = data.getBooleanExtra("isChecked", false);
                        if (!StringUtils.isEmpty(path)) {
                                type = 1;
                                selected(false, true, false);
                        }
                        Log.d("SpeechSetupActivity", "文字转语音；" + path + ",,,," + isChecked);
                }
        }

        /**
         * 设置三个按钮的选中状态
         */
        private void selected(boolean a, boolean b, boolean c) {
                rlLocalSpeech.setSelected(a);
                rlTextToSpeech.setSelected(b);
                rlRecord.setSelected(c);
        }

        /**
         * 设置超时
         * @return
         */
        private OkHttpClient setTimeOut(){
                OkHttpClient client = new OkHttpClient.Builder()
                        .connectTimeout(TIMEOUT, TimeUnit.SECONDS)
                        .writeTimeout(TIMEOUT, TimeUnit.SECONDS)
                        .readTimeout(TIMEOUT, TimeUnit.SECONDS)
                        .build();
                return client;

        }

}
